package org.socialresume.client.mvp.view.widget;

import org.socialresume.client.model.FeedItem;
import org.socialresume.client.model.TwitterFeed;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class TwitterUpdateWidget extends UpdateWidget {

	private boolean showUserLogin = false;
	
	public TwitterUpdateWidget(TwitterFeed feed, FeedItem item) {
		super(feed, item);
	}
	
	@Override
	protected Widget createFeedRepresentation() {
		FlexTable table = new FlexTable();
		HorizontalPanel content = new HorizontalPanel();
		HorizontalPanel legend = new HorizontalPanel();
		
		String login = ((TwitterFeed)feed).getTwitterLogin();
		String loginLink = "";
		if(showUserLogin){
			loginLink += "<a href='http://www.twitter.com/"+login+"'>@"+login+"</a>";
		}
		String messageContent = parseTwitt(item.getContent());
		Label label = new HTML(loginLink+messageContent);
		label.setStyleName("update");
		content.add(label);
		legend.add(new Label("date : "+dateFormat.format(item.getDate())));
		
		table.setWidget(0, 0, new Image(item.getInfos().get(TwitterFeed.TwitterFeedInfoEnum.PROFIL_LOGO_URL.getKey())));
		table.setWidget(0, 1, content);
		table.setWidget(1, 0, legend);
		table.getFlexCellFormatter().setRowSpan(0, 0, 2);
		return table;
	}

	private String parseTwitt(String content) {
		String[] string = content.split(" ");
		StringBuffer buffer = new StringBuffer();
		for (String string2 : string) {
			if(string2.startsWith("@")){
				String login ="<a href='http://twitter.com/"+string2.substring(1).replace(":","")+"'>"+string2+"</a>";
				buffer.append(login);
			}else if(string2.startsWith("http://")){
				String href ="<a href='"+string2+"'>"+string2+"</a>";
				buffer.append(href);
			}else{
				buffer.append(string2);
			}
			buffer.append(" ");
		}
		return buffer.toString();
	}

}
